package com.fly.estore.framework.session.Impl;

import com.fly.estore.domain.AccountInfo;
import com.fly.estore.framework.session.AccountSession;
import com.fly.estore.framework.session.SessionManager;
import com.fly.estore.framework.util.CommonUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by Fly on 2016/3/25.
 */
public class SessionManagerImpl implements SessionManager {

    private final int ACCOUNT_SESSION_INTERVAL = 2 * 60 * 60;

    public String createAccountSession(HttpServletRequest request, AccountInfo accountInfo) {
        AccountSession accountSession = new AccountSession();
        accountSession.setSessionId(CommonUtil.genPK());
        accountSession.setAccountId(accountInfo.getAccountId());
        accountSession.setAccountName(accountInfo.getAccountName());
//        accountSession.setHeaderPic(accountInfo.);

        HttpSession session = request.getSession();
        session.setAttribute(accountSession.getSessionId(), accountSession);
        session.setMaxInactiveInterval(ACCOUNT_SESSION_INTERVAL);
        return accountSession.getSessionId();
    }

    public AccountSession updateAccountSession(HttpServletRequest request, String sessionId) {
        HttpSession session = request.getSession();
        AccountSession accountSession = null;
        if (null != session.getAttribute(sessionId)){
            //session存在，更新session的有效期限
            session.setMaxInactiveInterval(ACCOUNT_SESSION_INTERVAL);
        }
        return accountSession;
    }

    public AccountSession getAccountSession(HttpServletRequest request, String sessionId) {
        HttpSession session = request.getSession();
        AccountSession accountSession = null;
        if (null != session.getAttribute(sessionId)){
            accountSession = (AccountSession)session.getAttribute(sessionId);
        }
        return accountSession;
    }

    public void removeAccountSession(HttpServletRequest request, String sessionId) {
        HttpSession session = request.getSession();
        if (null != session.getAttribute(sessionId)){
            session.setAttribute(sessionId, null);
            session.setMaxInactiveInterval(0);
        }
    }
}
